<script setup lang="ts">
import type { RecordListItem, RecordSearchRequest } from '@/types/api/record'
import { recordApi } from '@/request/api'
import { useDevice, useProfile, useRecord } from '@/stores'
import { useNav, useRelaunch, useToast } from '@/utils'
import { useHasPermission } from '@/utils/permission/permission'
import {
  onHide,
  onPullDownRefresh,
  onReachBottom,
  onShow,
} from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { isEmpty } from 'lodash-es'
import { reactive, ref } from 'vue'
import recordListItem from './components/record-list-item.vue'
import recordQrcode from './components/record-qrcode.vue'

const device = useDevice()
const profile = useProfile()
const record = useRecord()
const propsPopup = {
  mode: 'bottom',
  safeAreaInsetTop: true,
  closeable: true,
  round: 10,
  safeAreaInsetBottom: true,
}
let refreshRecordInterval: any = null
const statusList = [
  {
    name: '全部',
    value: '',
  },
  {
    name: '待审',
    value: '0',
  },
  {
    name: '拒绝',
    value: '2',
  },
  {
    name: '通过',
    value: '1',
  },
]
const popup = ref()
const recordQrcodeRef = ref()
const load = reactive({
  pageSize: 10,
  pageNum: 1,
  status: '',
  once: false,
  more: false,
})
const search = reactive<RecordSearchRequest>({
  identNumber: '',
  phone: '',
  name: '',
})
const statusKey = ref<string>('')
const recordList = ref<RecordListItem[]>()

onShow(async () => {
  if (!profile.isLoggedIn) {
    useToast('请先登录')
    useRelaunch('/me/login')
    return
  }
  refreshRecordInterval = setInterval(() => {
    getList()
  }, 1000 * 3)
  getList()
})
onHide(() => {
  clearInterval(refreshRecordInterval)
  refreshRecordInterval = null
})

onPullDownRefresh(async () => {
  if (!profile.isLoggedIn || !load.once) {
    uni.stopPullDownRefresh()
    return
  }
  load.pageNum = 1
  load.more = true
  load.once = false
  recordList.value = []
  await getList()
  uni.stopPullDownRefresh()
})
onReachBottom(async () => {
  if (!load.once || !load.more) {
    return
  }
  load.pageNum += 1
  getList()
})

function openPopup() {
  popup.value.open()
}
function clonePopup() {
  search.phone = ''
  search.name = ''
  popup.value.close()
}
function onPopupSearch() {
  popup.value.close()
  getList()
}
function onStatus(item: { name: string, value: string }) {
  statusKey.value = item.value
  load.status = item.value
  getList()
}
function onQrCode() {
  recordQrcodeRef.value.open()
}
async function onRecordDetail(item: RecordListItem) {
  record.update(item)
  useNav('/record/details')
}

async function getList() {
  load.once = false
  const [err, res] = await to(
    recordApi.page({
      pageSize: load.pageSize,
      pageNum: load.pageNum,
      status: load.status,
      ...search,
    }),
  )
  load.once = true
  if (err) {
    return
  }
  recordList.value = res.list
  load.more = load.pageNum < res.totalPage

  if (load.pageNum === 1) {
    recordList.value = res.list
  }
  else {
    recordList.value = [...recordList.value, ...res.list]
  }
}
</script>

<template>
  <view class="home relative">
    <!-- 渐变背景 -->
    <view class="absolute top-0 w-full">
      <!-- #ifndef H5 -->
      <view
        class="relative"
        :style="{ height: `${device.menuButtonStyle.bottom + usePx(10)}px` }"
      ></view>
      <!-- #endif -->
      <view class="relative h-370px"></view>
      <view class="absolute top-0 h-full w-full">
        <image
          class="absolute h-full w-full"
          src="~@/static/pagebg.jpeg"
          mode="aspectFill"
        ></image>
        <view
          class="absolute bottom-0 h-270px w-full from-transparent to-theme-pagebg bg-gradient-to-b"
        ></view>
      </view>
    </view>
    <!-- 搜索 -->
    <view class="relative top-20px w-full p-b-120px">
      <view class="flex items-center justify-center px-20px">
        <view
          class="br flex items-center justify-between rd-10px bg-white p-l-15px p-r-20px"
        >
          <view class="h-60px w-590px flex items-center rounded-full">
            <view class="">
              <uv-icon size="25" name="search"></uv-icon>
            </view>
            <view
              class="m-r-15px w-480px b-r-1px b-r-#e0 b-r-solid p-l-15px p-r-10px"
            >
              <input
                v-model="search.identNumber"
                clearable
                placeholder="身份证号"
              >
            </view>
          </view>
          <view @click="getList"> 搜索</view>
        </view>
      </view>
      <!-- 选择 -->
      <view class="mt-10px mt-25px flex justify-between px-30px">
        <view class="flex">
          <view
            v-for="item in statusList"
            :key="item.value"
            class="mr-10px rd-10px bg-white px-2 py-1 text-24px lh-30px"
            :class="item.value === statusKey ? 'text-theme-primary' : ''"
            @click="onStatus(item)"
          >{{ item.name }}</view>
        </view>
        <view class="flex items-center text-25px" @click="openPopup">
          筛选
          <view class="ml-10px">
            <uv-icon size="18" name="arrow-down"></uv-icon>
          </view>
        </view>
      </view>
      <!-- 二维码  -->
      <view class="mt-25px flex justify-end px-25px">
        <view
          class="btn-primary-theme rd-30px px-4 py-2 text-center text-23px text-white"
          @click="onQrCode"
        >
          二维码录入
        </view>
      </view>
      <!-- 列表 -->
      <view class="mt-20px px-25px">
        <template v-for="item in recordList" :key="item.id">
          <view
            class="mt-10px flex b-b-1px b-b-#e0 b-b-solid bg-white px-20px py-25px"
            @click="onRecordDetail(item)"
          >
            <record-list-item :item="item" @update="getList"></record-list-item>
          </view>
        </template>
        <view class="text-center text-30px text-gray-400 lh-100px">
          <view v-if="!profile.isLoggedIn" class="lh-750px">您还未登录，请先登录~</view>
          <template v-else>
            <template v-if="!load.once">加载中...</template>
            <template v-else>
              <template v-if="load.more">继续加载</template>
              <template v-else>
                <view v-if="isEmpty(recordList)" class="lh-750px">暂无数据</view>
                <template v-else>没有了</template>
              </template>
            </template>
          </template>
        </view>
      </view>
    </view>
    <uv-popup
      ref="popup"
      :mode="propsPopup.mode"
      :safe-area-inset-top="propsPopup.safeAreaInsetTop"
      :closeable="propsPopup.closeable"
      :round="propsPopup.round"
      :safe-area-inset-bottom="propsPopup.propsPopup"
    >
      <template #default>
        <view class="w-hull h-1000px flex flex-col justify-between">
          <view class="flex-1">
            <view class="mt-80px px-3">
              <p class="text-28px text-gray-600">姓名</p>
              <uv-input
                v-model="search.name"
                class="mt-20px"
                placeholder="请输入姓名"
                border="surround"
                clearable
              ></uv-input>
            </view>
            <view class="mt-30px px-3">
              <p class="text-28px text-gray-600">手机号</p>
              <uv-input
                v-model="search.phone"
                class="mt-20px"
                placeholder="请输入手机号"
                border="surround"
                clearable
              ></uv-input>
            </view>
          </view>
          <view class="mb-130px flex justify-around px-3">
            <uv-button
              text="清空"
              class="w-300px"
              @click="clonePopup"
            ></uv-button>
            <uv-button
              type="primary"
              text="确定"
              class="w-300px"
              @click="onPopupSearch"
            ></uv-button>
          </view>
        </view>
      </template>
    </uv-popup>

    <record-qrcode ref="recordQrcodeRef"></record-qrcode>
  </view>
</template>

<style less scoped>
.text {
  color: #4adb36;
}
.home {
  background-color: #edf2fa;
  min-height: 100vh;
}
</style>
